import { EventTarget, sys } from 'cc';
import { WXUtils } from './WXUtils';
// 消息事件
export const gameEvent = new EventTarget();
// emit的事件类型
export enum GameEventType {
    CODE_CLICK = 'code-click',
    GAME_SUCCESS = 'game-success',
    GAME_TIMER_STOP = 'game-timer-stop',
    ADVERT = 'advert',
}
// emit的广告的值
export enum AdvertType {
    AD_SHOW = 'advert_show',
    AD_ERROR = 'advert_error',
    AD_SUCCESS = 'advert_success',
    AD_CLOSE = 'advert_close',
}

export enum RankMesgType {
    /** 全部排行榜 */
    RANK_ALL = 'rank_all',
}
// 进度条计时
export class GameTimer {

    static time: number = 0;

    static state: 'playing' | 'paused' | 'stopped' = 'playing';

    static play(time?: number) {
        if (time) { GameTimer.time = time; }
        if (GameTimer.time === 0) return;
        GameTimer.state = 'playing';
        console.log('计时开始');

    }

    static pause() {
        GameTimer.state = 'paused';
        console.log('计时暂停');
    }
    static stop() {
        GameTimer.state = 'stopped';
        console.log('计时结束');

        gameEvent.emit(GameEventType.GAME_TIMER_STOP, GameEventType.GAME_TIMER_STOP);
    }
}
// 本地存储
export class GameStorage {
    static setItem(key: string, value: any) { sys.localStorage.setItem(key, value) }
    static getItem(key: string) {
        return sys.localStorage.getItem(key)
    }
    static removeItem(key: string) {
        sys.localStorage.removeItem(key)
    }
    static clear() {
        sys.localStorage.clear()
    }

}

// 关卡数据
export class LevelData {
    static level: number = 1;
    static time: number = 0;
}

// 本地存储的key
export enum StorageKey {
    LEVEL = "level",
    MAX_LEVEL = "max_level",
    GAME_TIME = "game_info"
}

/**
 * 同步排行榜数据
 */
export class RankCloundData {
    static userInfo: any = null

    static async pushData() {
        if (!RankCloundData.userInfo) {
            // 授权
            const isOK = await WXUtils.openPrivacyContract()
            if (!isOK) return
            // 1 获取用户信息
            RankCloundData.userInfo = await WXUtils.getUserInfo()
        }
        const nickName = RankCloundData.userInfo.nickName
        const avatarUrl = RankCloundData.userInfo.avatarUrl
        const level = GameStorage.getItem(StorageKey.LEVEL)
        const maxLevel = GameStorage.getItem(StorageKey.MAX_LEVEL)

        const data = {
            nickName,
            avatarUrl,
            level,
            maxLevel
        }

        const result = await WXUtils.setUserCloudStorage(data)
        if (result) {
            console.log('同步排行榜数据成功');
        }
    }
}